package com.example.jvm;

import com.example.jvm.wheninit.MyClass;
import com.example.jvm.wheninit.MySubClass;
import com.example.jvm.whenload.MyClassLoader;

import java.lang.reflect.InvocationTargetException;

public class Main {

    static {
        System.out.println("Main class is static");
    }

    public static void main(String[] args) {
        loadClass();
    }

    public static void arrayType(){
        MyClass[][] myClassArray = new MyClass[10][10];
        System.out.println(myClassArray.getClass().getName());
    }

    public static void loadClass(){
        Class<?> clazz;
        MyClassLoader myClassLoader = new MyClassLoader();
        try {
            clazz = myClassLoader.loadClass("NotClass.class");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Object instance;
        try {
            instance = clazz.getDeclaredConstructors()[0].newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        try {
            clazz.getMethod("myMethod").invoke(instance);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下面几种情况会出发类的初始化
     */
    public static void init(){
        //调用静态字段 getstatic or putstatic
        int myStaticField = MyClass.myStaticField;
        MyClass.myStaticField = myStaticField + 1;
        //调用静态方法 invokestatic
        MyClass.myStaticMethod();
        //子类初始化
        int myStaticField1 = MySubClass.myStaticField;
        //接口包含default方法，实现类初始化
        int myStaticField2 = MySubClass.myStaticField;
    }

    /**
     * 下列不会出发初始化
     */
    public static void nonInit(){
        //常量在编译期就被放入常量池，调用常量不会处罚类初始化
        int constant = MyClass.CONSTANT;
        //调用父类静态字段，子类本身不会初始化
        int myStaticField1 = MySubClass.myStaticField1;
        //newarray
        MyClass[] myClasses = new MyClass[2];
        System.out.println(myClasses.getClass());
    }
}
